package com.xj.community.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class TestController {

    @RequestMapping(path = "/createCookie")
    @ResponseBody
    public String createCookie(HttpServletResponse response) {
        Cookie cookie1 = new Cookie("name", "damon");
        Cookie cookie2 = new Cookie("sex", "male");
        cookie2.setMaxAge(60*10);
        cookie1.setMaxAge(60*10);//设置最大生存时间
        cookie1.setPath("/community/getCookie");//设置有效访问路径，及怎样的请求才会携带该cookie信息
        cookie2.setPath("/community/getCookie");
        response.addCookie(cookie1);
        response.addCookie(cookie2);//将cookie添加到相应结果中
        return "create cookie";
    }

    @RequestMapping(path = "/getCookie")
    @ResponseBody
    public String getCookie(@CookieValue("name") String name,@CookieValue("sex") String sex){
        System.out.println(name);
        System.out.println(sex);
        return "get Cookie";
    }

    @RequestMapping(path = "/createSession")
    @ResponseBody
    public String createSession(HttpSession session){
        session.setAttribute("address","guangzhou");
        return "create session";
    }

    @RequestMapping(path = "/setSession")
    @ResponseBody
    public String setSession(HttpSession session){
        System.out.println(session.getAttribute("address"));
        return "set Session";
    }

    @RequestMapping(path="/test1")
    @ResponseBody
    public String test1(HttpServletRequest request){
        System.out.println(request.getParameter("field"));
        return "test1";
    }
}
